package com.afterRain.admin.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.afterRain.commonly.CommonlyRecord;
import com.afterRain.commonly.Prompt;
import com.afterRain.model.Admin;
import com.afterRain.model.UserFile;
import com.afterRain.util.FileUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

/**
* @author 作者 E-mail:
* @version 创建时间：2017年6月6日 上午11:36:29
* 类说明
*/
public class UploadFileController extends Controller{

	public void file(){
		List<UploadFile> uploadFiles = getFiles();
		String[] type = getParaValues("type");
		Admin admin1 = getSessionAttr(CommonlyRecord.SESSION_USER.name());
		for (int j = 0; j < type.length; j++) {
			UploadFile uploadFile = uploadFiles.get(j);
			List<UserFile> list = UserFile.dao.find("select * from user_file where user_id=? and `type`=? and `name`=?",admin1.getId(),type[j],uploadFile.getFileName());
			if(list.size()>0){
				renderJson(Prompt.filerepeat);
				return;
			}
		}
		for (int j = 0; j < type.length; j++) {
			UploadFile uploadFile = uploadFiles.get(j);
			String url = FileUtil.fileUploadRename(uploadFile, admin1.getAccount(), type[j], uploadFile.getFileName(), true);
			if(url != null){
				UserFile file = new UserFile();
				file.setName(uploadFile.getFileName());
				file.setUrl(url);
				file.setUserId(admin1.getId());
				file.setType(type[j]);
				file.setCreateDate(new Date());
				file.save();
			}
		}
		renderJson(Prompt.success);
	}
	
	public void uploadPage(){
		int page = getParaToInt("page")==null?1:getParaToInt("page");
		int pageSize = getParaToInt("pageSize")==null?10:getParaToInt("pageSize");
		Admin admin1 = getSessionAttr(CommonlyRecord.SESSION_USER.name());
		Page<UserFile> list = UserFile.dao.paginateByFullSql(page, pageSize, "select count(id) from `user_file` where user_id=?","select * from `user_file` where user_id=?",admin1.getId());
		setAttr("data", list);
		render("list.ftl");
	}
	
	public void insertUpdatPage(){
		int id =getParaToInt("id")==null?0:getParaToInt("id");
		Admin admin1 = getSessionAttr(CommonlyRecord.SESSION_USER.name());
		if(id==0){
			UserFile file = UserFile.dao.findFirst("select * from user_file where user_id=? and id=?", admin1.getId(),id);
			setAttr("file", file);
		}
		render("info.ftl");
	}
	
	public void deleteById(){
		int id =getParaToInt("id")==null?0:getParaToInt("id");
		Admin admin1 = getSessionAttr(CommonlyRecord.SESSION_USER.name());
		UserFile file = UserFile.dao.findFirst("select * from user_file where user_id=? and id=?", admin1.getId(),id);
		if(file == null){
			renderJson(Prompt.deleteerror);
			return;
		}
		if(file.delete()){
			renderJson(Prompt.success);
			return;
		}
		renderJson(Prompt.deleteerror);
		return;
	}
}
